package masking.wechat.sdk.h5;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import masking.wechat.sdk.AccessToken4Json;
import masking.wechat.sdk.MPAccount;
import masking.wechat.sdk.WechatUserInfo;
import masking.wechat.sdk.util.EncryptUtils;
import masking.wechat.sdk.util.HttpUtils;
import masking.wechat.sdk.util.JacksonUtils;

public class WechatH5Util {
	
	public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	public static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";    
	
	/**
	 * 生成微信OAuth登录url
	 * @param redirectUrl  登录成功后跳转地址, 不设置默认首页
	 * @param mp
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String genLoginUrl(String redirectUrl, MPAccount mp) throws UnsupportedEncodingException {
		StringBuilder loginUrl = new StringBuilder(mp.getLoginUri());
		
		loginUrl.append("?appid=");
		loginUrl.append(mp.getAppId());
		
		String loginRedirectUrl = mp.getRedirectUri(); //实际传给微信的回跳地址
		
		if(StringUtils.isNotBlank(redirectUrl)) { //微信回跳回应用, 应用处理完成后的二次跳转地址
			redirectUrl=URLEncoder.encode(redirectUrl, "utf-8");
			loginRedirectUrl += ("?redirectUrl="+redirectUrl);
		}
		
		loginUrl.append("&redirect_uri=");
		loginUrl.append(URLEncoder.encode(loginRedirectUrl, "utf-8"));

		
		loginUrl.append("&response_type=code&scope=");
		loginUrl.append(mp.getScope());
		loginUrl.append("#wechat_redirect");
		return loginUrl.toString();
	}
	
	/**
	 * 根据code获取用户accessToken
	 * @param code
	 * @param mp
	 * @return
	 * @throws IOException 
	 */
	public static AccessToken4Json getUserAccessToken(String code, MPAccount mp) throws IOException {
		StringBuilder url = new StringBuilder(ACCESS_TOKEN_URL);
		
		url.append("?appid=");
		url.append(mp.getAppId());
		
		url.append("&secret=");
		url.append(mp.getSecret());
		
		url.append("&code=");
		url.append(code);
		url.append("&grant_type=authorization_code");
		
		String response = HttpUtils.get(url.toString());
		return JacksonUtils.getInstance().fromJson(response, AccessToken4Json.class);
	}
	
	/**
	 * 根据accessToken获取UserInfo
	 * @param accessToken
	 * @param pf
	 * @return
	 * @throws IOException 
	 */
	public static WechatUserInfo getUserInfo(String access_token, String openid) throws IOException {
		StringBuilder url = new StringBuilder(USER_INFO_URL);
		url.append("?access_token=");
		url.append(access_token);
		url.append("&openid=");
		url.append(openid);
		
		String response = HttpUtils.get(url.toString());
		return JacksonUtils.getInstance().fromJson(response, WechatUserInfo.class);
	}
	
	/**
	 * 获取指定url需要的jsconfig
	 * @param url
	 * @return
	 */
	public static JsConfig getJsConfig(String url, MPAccount mp) {
		JsConfig conf = new JsConfig();
    	conf.setAppId(mp.getAppId());
    	Date now = new Date();
    	conf.setTimestamp(now.getTime()/1000);
    	conf.setNonceStr(EncryptUtils.getRandomString(16));
    	
    	String raw;
		try {
			raw = "jsapi_ticket="+MpJsapiTicket.get(mp)
							+"&noncestr="+conf.getNonceStr()
							+"&timestamp="+conf.getTimestamp()
							+"&url="+url;
	    	conf.setSignature(EncryptUtils.sha1(raw));
	    	conf.setValid(true);
		} catch (Exception e) {
			conf.setSignature("Error, Exception in signature! Try later!");
		}
		return conf;  
	}
}
